package com.sskj.candy.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sskj.candy.R;
import com.sskj.candy.R2;
import com.sskj.candy.adapter.BaseAdapter;
import com.sskj.candy.adapter.ViewHolder;
import com.sskj.candy.bean.BalanceCqtfBean;
import com.sskj.candy.bean.CandyBean;
import com.sskj.candy.bean.CandyRankBean;
import com.sskj.candy.bean.CandyTextBean;
import com.sskj.candy.bean.Water;
import com.sskj.candy.component.DaggerUserDataComponent;
import com.sskj.candy.presenter.CandyFragmentPresenter;
import com.sskj.candy.view.WaterView;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.TipUtil;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.CANDY_MAIN)
public class CandyFragment extends BaseFragment<CandyFragmentPresenter> {
    @BindView(R2.id.top)
    LinearLayout top;
    @BindView(R2.id.mine_ll)
    LinearLayout mineLl;
    @BindView(R2.id.usab_cqtf)
    TextView usabCqtf;
    @BindView(R2.id.water_view)
    WaterView waterView;
    @BindView(R2.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    private int page = 1;
    @BindView(R2.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private BaseAdapter<CandyRankBean> adapter;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private int size = 10;
    private View inflate;
    private Disposable noticeDispo;

    @Override
    protected int getLayoutId() {
        return R.layout.candy_fragment_main;
    }

    @Override
    public CandyFragmentPresenter getPresenter() {
        return new CandyFragmentPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        HashMap<String, Integer> rankMap = new HashMap<>();
        rankMap.put("1",R.mipmap.candy_no1);
        rankMap.put("2",R.mipmap.candy_no2);
        rankMap.put("3",R.mipmap.candy_no3);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 28);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.candy_0A1));
            return textView;
        });
        ClickUtil.click(mineLl, () -> {
            ARouter.getInstance().build(RConfig.CANDY_RECORD).navigation();
        });
        waterView.setOnWaterViewClick((waterData, view) -> mPresenter.getSuger(waterData, view, waterData.getId()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setFirstDraw(false)
                .setLastDraw(false)
                .setDividerColor(color(R.color.candy_BEC)));
        adapter = new BaseAdapter<CandyRankBean>(R.layout.candy_ranking, null, recyclerView, true) {
            @Override
            public void bind(ViewHolder holder, CandyRankBean item) {
                holder.setText(R.id.ranking, Integer.valueOf(item.getRank()) > 3 ? String.valueOf(item.getRank()) : "")
                        .setText(R.id.num_phone, item.getMobile())
                        .setText(R.id.num_money, item.getNum());
                TextView textView = holder.getView(R.id.ranking);
                if (Integer.valueOf(item.getRank())<=3){
                    textView.setBackgroundResource(rankMap.get(item.getRank()));
                }else {
                    textView.setBackground(null);
                }
            }
        };
        adapter.setHeaderAndEmpty(true);
        inflate = LayoutInflater.from(getContext()).inflate(R.layout.candy_ranking_header, null);
        adapter.setHeaderView(inflate);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                mPresenter.getSugerRank(page, size);
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getSugerRank(page, size);
                mPresenter.getSugerRecord(1);
                mPresenter.getBalance();
            }
        });
    }

    public void stopRefresh() {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();
    }

    @Override
    public void onResume() {
        if (mPresenter!=null){
            mPresenter.getBalance();
        }
        super.onResume();
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.getSugerRank(page, size);
        mPresenter.getSugerRecord(1);
        mPresenter.finanBanner();// 获取轮播
        mPresenter.getBalance();
    }

    public void update(CandyBean data) {
        stopRefresh();
//        if (data.getMy().getRank().equals("") != null) {
            ((TextView) inflate.findViewById(R.id.ranking)).setText(App.INSTANCE.getString(R.string.candy_candyFragment1_j)+String.valueOf(data.getMy().getRank()));
            ((TextView) inflate.findViewById(R.id.num_phone)).setText(data.getMy().getMobile());
            ((TextView) inflate.findViewById(R.id.num_money)).setText(data.getMy().getNum());
//        } else {
//            ((TextView) inflate.findViewById(R.id.ranking)).setText("----");
//            ((TextView) inflate.findViewById(R.id.num_phone)).setText(SPUtil.get(SPConfig.MOBILE, ""));
//            ((TextView) inflate.findViewById(R.id.num_money)).setText("----");
//        }
        if (page == 1) {
            adapter.setNewData(data.getRes());
        } else {
            adapter.addData(data.getRes());
        }
    }

    public void updateWaterList(List<Water> list) {
        waterView.setWaters(list);
    }

    public void removeView(Water water, View view) {
        waterView.removeWater(view);
        TipUtil.showAward(getContext(), App.INSTANCE.getString(R.string.candy_candyFragment2_j) + water.getUsdt_num() + "CQTF", water.getUsdt_num());
    }

    public void updateBanner(CandyTextBean data) {
        if (tvNotice != null) {
            if (data.getRes().size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                String text = data.getRes().get((int) (i % data.getRes().size())).getMsg();
                                tvNotice.setText(text);

                            }
                        }, System.out::println);
            }
        }
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(noticeDispo);
        super.onDestroy();
    }

    public void updateBalance(BalanceCqtfBean data) {
        usabCqtf.setText(App.INSTANCE.getString(R.string.candy_candyFragment3_j)+data.getUsable() );

    }
}
